﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsImgView
{
    public partial class Form1 : Form
    {
        static private List<string> imageExtensions = new List<string> { ".jpg", ".jpeg", ".png", ".bmp", ".gif" };
        public Form1()
        {
            InitializeComponent();

            // 设置缩放模式
            pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string imgPath = textBox1.Text;
            if (imgPath.Length == 0)
            {
                MessageBox.Show("输入不能为空！", "Error");
                return;
            }

            // 加载路径下所有图片
            List<string> imagePaths = GetImagePaths(imgPath);
            if (imagePaths.Count == 0)
            {
                MessageBox.Show("该目录下没有图片！", "Error");
                return;
            }

            // 清空项，否则一直添加
            listBox1.Items.Clear();

            // 填充 ListBox
            foreach(string filePath in imagePaths)
            {
                listBox1.Items.Add(filePath);
            }

            // 点击 ListBox 项目，将图片显示到 PictureBox 上
        }

        static List<string> GetImagePaths(string imgPath)
        {
            List<string> imagePaths = new List<string>();

            // 确保目录是否存在
            if (Directory.Exists(imgPath))
            {
                foreach(string filePath in Directory.GetFiles(imgPath, "*", SearchOption.AllDirectories))
                {
                    //检查是否为图片类型
                    if (imageExtensions.Contains(Path.GetExtension(filePath).ToLowerInvariant())){
                        imagePaths.Add(Path.GetFullPath(filePath));
                    }
                        
                }
            }else
            {
                MessageBox.Show("目录不存在！", "Error");
            }

            return imagePaths;
        }

        // ListBox 项选中事件
        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string imgPath = listBox1.SelectedItem.ToString();
            pictureBox1.Load(imgPath);
        }
    }
}
